//
//  LFZTabItem.swift
//  Swift微博
//
//  Created by MagicalStar Pro on 15/12/29.
//  Copyright © 2015年 liang. All rights reserved.
//

import UIKit

@objc protocol LFZTabItemDelegate :NSObjectProtocol
{
   optional func LFZTabItemWithButton(button:UIButton)
}

class LFZTabItem: UIView {
    
    var selectedButton :UIButton?
    var delegaate :LFZTabItemDelegate?
    
    lazy var buttons : [UIButton]? = {
        var button = [UIButton]()
        
        return button
    }()
    
    lazy var centerButton :UIButton? = {
        
        let button = UIButton()
        
        button.setImage(UIImage(named: ""), forState: UIControlState.Normal)
        
        return button
    }()
    
    func addSubviewWithImageArray(array : [NSObject] ) {
        
        for i in 0...array.count - 1 {
            
            let dict = array[i] as! [String : NSObject]
            
            let button = LFZItemButton()
            button.tag = i
            button.setImage( UIImage(named: dict["Normal"]! as! String ) , forState: UIControlState.Normal)
            
            button.setImage( UIImage(named: dict["Selected"]! as! String ) , forState: UIControlState.Selected)
            
            button.setTitle(dict["title"]! as? String, forState: UIControlState.Normal)
            
            button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
            
            button.addTarget(self, action: Selector("buttonClick:"), forControlEvents: UIControlEvents.TouchUpInside)
            
            buttons?.append(button)
            addSubview(button)
            
            if i == 0
            {
                button.selected = true
                selectedButton = button
            }
            
        }
    }
    
    func buttonClick(button :UIButton)
    {
        
        selectedButton?.selected = false
        button.selected = true
        selectedButton = button
        
            delegaate?.LFZTabItemWithButton?(button)
        
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()

        var i =  CGFloat(0)
        
        let selfWid = bounds.size.width
        
        print(selfWid)
        let wid = selfWid / CGFloat(((buttons?.count) ?? 0)+1)

        let hit = bounds.size.height
        
        
        for button in subviews {
            
            if i == 2 {
                i = 3
            }
            button.frame = CGRectMake(wid*i, 0, wid, hit)
            i++
        }
        
        addSubview(centerButton!)
        centerButton?.bounds = CGRectMake(0, 0, wid, hit)
        centerButton?.center = center
        
    }

}
